package com.xsd.awen.utils;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class IdUtils {

    public static boolean hasDuplicates(List<String> list) {
        // 将 List 转换为 HashSet
        HashSet<String> set = new HashSet<>(list);
        // 如果 HashSet 的大小与 List 的大小不同，说明有重复元素
        return set.size() < list.size();
    }


    public static void main(String[] args){
        List<String> abcs = Lists.newArrayList();
        for ( int i=0 ; i<10000 ; i++ ){
            abcs.add(uuid());
        }

       /* for( String val : abcs ){
            System.out.println(val);
        }

        System.out.println(GsonUtils.toJson(ids));*/
        System.out.println("Has duplicates? " + hasDuplicates(abcs));
    }

    private static long currTime = -1;
    private static Map<Long, List<String>> ids = Maps.newHashmap();

    // 38 char
    public static String generate(String consumerId){
        return consumerId + uuid();
    }

    // 19 char
    public static String uuid(){
        double random = new Random().nextDouble();
        String value = String.valueOf(random).substring(2,8);

        long time = System.currentTimeMillis();

        if( time != currTime ){
            ids = Maps.newHashmap();
            currTime = time;
            List<String> values = ids.get(time);

            if( values == null ){
               values = Lists.newArrayList();
               ids.put(time,values);
            }
            values.add(value);
            return time + value;
        }else{
            List<String> values = ids.get(time);
            if( values != null ){
                for( String val : values ){
                    if( val.equals(value) ){
                        return uuid();
                    }
                }
                values.add(value);
                return time + value;
            }else{
                values = Lists.newArrayList();
                values.add(value);
                ids.put(time,values);
                return time + value;
            }
        }
    }

}
